package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

type Article struct {
	Id          int    `orm="auto;pk"`
	Author      string `orm="size(16)"`
	Title       string `orm="size(64)"`
	Content     string
	Create_time int64
}

func Init() {
	orm.RegisterModel(new(Article))
}

// 查询所有
func QueryArticleAll() []Article {
	o := orm.NewOrm()
	qs := o.QueryTable("article")

	var articles []Article
	count, err := qs.Filter("id__gt", 0).OrderBy("-id").All(&articles)
	if err == nil {
		fmt.Printf("count", count)
	}
	return articles
}

// 查询(id)
func QueryArticleById(id int) (Article, bool) {
	o := orm.NewOrm()
	article := Article{Id: id}
	err := o.Read(&article)
	if err == orm.ErrNoRows {
		fmt.Println("查询不到~")
		return article, false
	} else if err == orm.ErrMissPK {
		fmt.Println("找不到主键~")
		return article, false
	} else {
		return article, true
	}
}

// 创建
func CreateArticle(author string, title string, content string) (int64, bool) {
	o := orm.NewOrm()

	article := new(Article)
	article.Author = author
	article.Title = title
	article.Content = content
	article.Create_time = time.Now().Unix()

	id, err := o.Insert(article)
	if err == nil {
		fmt.Println("创建成功~")
		return id, true
	} else {
		fmt.Println("创建失败~")
		return id, false
	}
}

// 更新
func UpdateArticleById(id int, table string, fields map[string]interface{}) bool {
	o := orm.NewOrm()
	_, err := o.QueryTable(
		table).Filter(
		"Id", id).Update(
		fields)
	if err == nil {
		fmt.Println("更新成功~")
		return true
	}
	fmt.Println("更新失败~")
	return false
}

// 删除(id)
func DeleteArticle(id int) bool {
	o := orm.NewOrm()
	article := Article{Id: id}
	num, err := o.Delete(&article)
	if err == nil {
		fmt.Println("删除影响的行:", num)
		return true
	} else {
		return false
	}
}
